package com.movie.config;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.TemplateType;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.FileSystemResource;

import java.io.File;
import java.util.Collections;
import java.util.Properties;

/**
 * MyBatis-Plus 的代码生成器
 */
public class MPCodeGenerator {

    private static Properties loadYml(String filePath) {
        YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
        factoryBean.setResources(new FileSystemResource(filePath));
        return factoryBean.getObject();
    }

    public static void main(String[] args) {
        String projectPath = System.getProperty("user.dir");
        Properties properties = loadYml(String.join(File.separator, projectPath, "src", "main", "resources", "application.yml"));

        FastAutoGenerator.create(
                properties.getProperty("spring.datasource.url"),
                properties.getProperty("spring.datasource.username"), properties.getProperty("spring.datasource.password")).globalConfig(builder -> {
            builder.author("Liu Jiaquan") // 设置作者
                    .fileOverride() // 覆盖已生成文件
                    .disableOpenDir().dateType(DateType.ONLY_DATE).outputDir(projectPath + "/two-ticket-server/src/main/java"); // 指定输出目录
        }).packageConfig(builder -> {
            builder.parent("com.movie") // 设置父包名
                    .mapper("mapper").entity("bean").pathInfo(Collections.singletonMap(OutputFile.mapperXml,
                            projectPath + "/two-ticket-server/src/main/resources/mapper/templateLibraryConfig/")); // 设置mapperXml生成路径
        }).strategyConfig(builder -> {
            builder.addInclude("myfavoritemovie") // 设置需要生成的表名
                    .addTablePrefix("t_", "c_"); // 设置过滤表前缀

            // Entity 策略配置
            builder.entityBuilder().naming(NamingStrategy.underline_to_camel)
                    .columnNaming(NamingStrategy.underline_to_camel).enableChainModel()
                    .enableTableFieldAnnotation().enableLombok();
        }).templateConfig(builder -> {
            builder.disable(TemplateType.SERVICE, TemplateType.SERVICEIMPL, TemplateType.CONTROLLER);
        }).templateEngine(new FreemarkerTemplateEngine()).execute();
    }

}
